import Collect from '../../../Models/collect';
import { saveNotice } from '../utils/';
import { getCreator } from '../../../utils/util';
const collectEntity = new Collect();

export function getCollects(req, res, next) {
    const { ...query } = req.body;
    const creator = getCreator(req.user);
    query.creatorId = creator._id;
    collectEntity.getCollects(query, (err, collects, total, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: { list: collects, total, hasMore } });
    })
}

export function getCollect(req, res, next) {
    const {  ...query } = req.body;
    collectEntity.getCollect(query, (err, collects) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json(collects);
    })
}

export function saveCollect(req, res, next) {
    const { ...collect } = req.body;
    const collectEntity = new Collect();
    const creator = getCreator(req.user);
    collectEntity.getCollect({creatorId: creator._id, postId: collect.postId}, (err, clt) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (clt) {
            return res.status(200).json({ code: 1, msg: '您已收藏该帖子' });
        }
        collect.creatorId = creator._id;
        collect.creator = creator;
        collectEntity.saveCollect(collect, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            const { url } = collect;
            const notice = {
                receiverId: creator._id,
                receiver: creator,
                url,
                msg: `有人收藏了您的帖子`,
                type: 'other',
                status: 0,
            }
            saveNotice(notice);
            return res.status(200).json({ code: 0 });
        });
    })
}

// export function updateCollect(req, res, next) {
//     const {  ...collect } = req.body;
//     const collectEntity = new Collect();
//     if (!collect._id) {
//         collectEntity.saveCollect(collect, err => {
//             if (err) {
//                 return res.status(200).json({ code: 1, msg: '服务器开小差' });
//             }
//             return res.status(200).json({ code: 0 });
//         });
//     } else {
//         collectEntity.updateCollect(collect, err => {
//             if (err) {
//                 return res.status(200).json({ code: 1, msg: '服务器开小差' });
//             }
//             return res.status(200).json({ code: 0 });
//         });
//     }
// }

export function removeCollects(req, res, next) {
    const collectIds = req.body.collectIds;

    collectEntity.removeCollects(collectIds, (err) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}
